<template>
    <nut-address
    v-model="value"
    v-model:visible="visible"
    :province="address[0]"
    :city="address[1]"
    :country="address[2]"
    :town="address[3]"
    @change="onChange"
    @close="onClose"
    custom-address-title="请选择所在地区"
  ></nut-address>
</template>

<script lang="ts" setup>
  import { districtApi } from '@/api/District';
  import { reactive, ref, watch } from 'vue';

  const props = withDefaults(defineProps<{
    maxLevel? : number
  }>(), {
    maxLevel : 4
  })

  const emit = defineEmits<{
    (e : 'confirm', value : {value : number[]; address : string[]}) : void;
  }>()

  const model = defineModel<number[]>({
    default : []
  })

  const value = ref<number[]>([]);

  const visible = defineModel<boolean>('visible', {default : false})


  const address = reactive<Array<Array<any>>>([[{}], [{}], [{}], [{}]]);


    async function restore() {
      value.value = [...model.value]
      for(let i = 0; i < (model.value.length - 1); i ++) {
        const data = await queryArea(model.value[i])
        address[i + 1] = data
      }

      const selectedAddress:string[] = []

      for(let i = 0; i < address.length; i ++) {
        let adr = address[i].find(item => item.id == value.value[i])
        selectedAddress.push(adr.name)
      }

      emit('confirm', {value : value.value, address : selectedAddress})

    } 


  watch(model, (newv, olov) => {
    if(newv.toString() != value.value.toString()) {
      restore()
    }
  })
    


  async function onChange(e) {
    const level = e.value.level
    if(level == props.maxLevel) {
      visible.value = false
      return
    }
    const data = await queryArea(e.value.id)
    address[level] = data
  }

  function onClose(e) {
    let newValue:number[] = [...model.value]
    let address:string[] = []
    const data = e.data
    if(data.province) {
      address.push(data.province.name)
      newValue[0] = data.province.id
    }
    if(data.city) {
      address.push(data.city.name)
      newValue[1] = data.city.id
    }
    if(data.country) {
      address.push(data.country.name)
      newValue[2] = data.country.id
    }
    if(data.town) {
      address.push(data.town.name)
      newValue[3] = data.town.id
    }

    value.value = [...newValue]
    model.value = [...newValue]

    emit('confirm', {value : value.value, address : address})
  }

  async function queryArea(id) {
      const r = await districtApi(id)
      return r.data || []
  }



  queryArea(0).then(data => {
      address[0] = data
  })


  if(model.value.length > 0) {
      value.value = [...model.value]
      restore()
  }
</script>